
#include "maincore.h"


MainCore::MainCore(QObject *parent) : QObject(parent), server(new RemoteServer(this))
{
}

void MainCore::addWid(int wid)
{
    m_widSet.insert(wid);
}

bool MainCore::listen(const QHostAddress &address, quint16 port)
{
    foreach (int wid, m_widSet)
    {
        CaptureServer *s = new CaptureServer(wid);
        m_widScreenMap.insert(wid, s);
        server->pushWindow(s->window());
        connect(server, &RemoteServer::startCap, s, &CaptureServer::start);
        connect(server, &RemoteServer::pauseCap, s, &CaptureServer::stop);
        connect(server, &RemoteServer::stopCap, s, &CaptureServer::stop);
        connect(server, &RemoteServer::receivedKey, this, &MainCore::on_receivedKey);
        connect(server, &RemoteServer::receivedMouse, this, &MainCore::on_receivedMouse);
        connect(server, &RemoteServer::receivedWheel, this, &MainCore::on_receivedWheel);
//        connect(server, &RemoteServer::receivedCutText)
        connect(s, &CaptureServer::outputStream, this, &MainCore::on_receivedFramebuffer);
    }
    return server->listen(address, port);
}

void MainCore::on_receivedFramebuffer(const QByteArray &buff)
{
    CaptureServer* screen = dynamic_cast<CaptureServer*>(sender());
    if(!screen)
    {
        return;
    }

    int wid = screen->window()->winId();
    server->sendWindowFramebuffer(wid, buff);
}

void MainCore::on_receivedMouse(int wid, int key, bool isPress, int x, int y)
{
    if(!m_widScreenMap.contains(wid))
    {
        return;
    }
    CaptureServer* screen = m_widScreenMap[wid];
    screen->window()->postMouseEvent(key, isPress, x, y);
}

void MainCore::on_receivedWheel(int wid, int delta)
{
    if(!m_widScreenMap.contains(wid))
    {
        return;
    }
    CaptureServer* screen = m_widScreenMap[wid];
    screen->window()->postWheelEvent(delta);
}

void MainCore::on_receivedKey(int wid, int key, bool isPress)
{
    if(!m_widScreenMap.contains(wid))
    {
        return;
    }
    CaptureServer* screen = m_widScreenMap[wid];
    screen->window()->postKeyEvent(key, isPress);
}
